package com.lmt.ymcc.mq.listener;

import com.alibaba.fastjson.JSONObject;
import com.lmt.ymcc.domain.CourseOrder;
import com.lmt.ymcc.dto.Order2PayParamDto;
import com.lmt.ymcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;

/**
 * @Description: TODO
 * @Author: Amazing
 * @Date: 2022/8/20 14:50
 * @Version: 1.0
 */

@RocketMQTransactionListener(txProducerGroup = "TxOrder2PayGroup") // 配置事务监听器组名
@Slf4j
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {


    @Autowired
    private ICourseOrderService courseOrderService;

    // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        if (o == null) {
            // 没参数，直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        CourseOrder courseOrder = (CourseOrder)o;
        // 执行本地事务
        try {
            courseOrderService.savaOrderAndItem(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    // 检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] body = (byte[]) message.getPayload();
            String jsonStr = new String(body, StandardCharsets.UTF_8);
            Order2PayParamDto order2PayParamDto = JSONObject.parseObject(jsonStr, Order2PayParamDto.class);
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(order2PayParamDto.getOrderNo());
            if(courseOrder != null){
                return RocketMQLocalTransactionState.COMMIT;//检查本地事务成功
            }
            return RocketMQLocalTransactionState.ROLLBACK;//检查本地事务执行失败
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;//到底本地事务执行成功与否我不知道
        }
    }
}
